import { ref, Ref } from 'vue'
import { ElMessage } from 'element-plus'

// API调用的通用Hook
export function useApi<T = any>() {
  const loading = ref(false)
  const data: Ref<T | null> = ref(null)
  const error = ref<string | null>(null)

  const execute = async <R = T>(
    apiCall: () => Promise<R>,
    options?: {
      showLoading?: boolean
      showError?: boolean
      successMessage?: string
    }
  ): Promise<R | null> => {
    const {
      showLoading = true,
      showError = true,
      successMessage
    } = options || {}

    try {
      if (showLoading) {
        loading.value = true
      }
      error.value = null

      const result = await apiCall()
      data.value = result as any
      
      if (successMessage) {
        ElMessage.success(successMessage)
      }
      
      return result
    } catch (err: any) {
      const errorMessage = err?.message || '请求失败'
      error.value = errorMessage
      
      if (showError) {
        ElMessage.error(errorMessage)
      }
      
      return null
    } finally {
      if (showLoading) {
        loading.value = false
      }
    }
  }

  return {
    loading,
    data,
    error,
    execute
  }
}

// 分页数据的Hook
export function usePagination<T = any>(
  apiCall: (params: any) => Promise<{ list: T[]; total: number }>,
  initialParams: any = {}
) {
  const loading = ref(false)
  const data = ref<T[]>([])
  const total = ref(0)
  const currentPage = ref(1)
  const pageSize = ref(10)
  const params = ref({ ...initialParams })

  const fetchData = async (resetPage = false) => {
    try {
      loading.value = true
      
      if (resetPage) {
        currentPage.value = 1
      }

      const result = await apiCall({
        ...params.value,
        page: currentPage.value,
        pageSize: pageSize.value
      })

      data.value = result.list
      total.value = result.total
    } catch (error) {
      console.error('获取数据失败:', error)
    } finally {
      loading.value = false
    }
  }

  const handlePageChange = (page: number) => {
    currentPage.value = page
    fetchData()
  }

  const handleSizeChange = (size: number) => {
    pageSize.value = size
    currentPage.value = 1
    fetchData()
  }

  const search = (searchParams: any) => {
    params.value = { ...params.value, ...searchParams }
    fetchData(true)
  }

  const refresh = () => {
    fetchData()
  }

  return {
    loading,
    data,
    total,
    currentPage,
    pageSize,
    params,
    fetchData,
    handlePageChange,
    handleSizeChange,
    search,
    refresh
  }
}